// =========================
// 小数四则运算精度问题解决
// =========================
const floatCalc = function (a, b, act) {
  let aStr = a + '';
  let bStr = b + '';
  var aNum = aStr.indexOf('.'),
    bNum = bStr.indexOf('.'),
    aSum,
    bSum,
    resultNum,
    inta,
    intb;

  aSum = aNum < 0 ? 0 : aStr.split('.')[1].length;
  bSum = bNum < 0 ? 0 : bStr.split('.')[1].length;
  resultNum = aSum > bSum ? aSum : bSum;
  inta =
    aNum < 0
      ? Number(aStr + (Math.pow(10, resultNum) + '').replace('1', ''))
      : (function () {
          aStr = aStr.replace('.', '');
          aStr =
            resultNum == aSum
              ? aStr
              : aStr + (Math.pow(10, resultNum - aSum) + '').replace('1', '');
          return Number(aStr);
        })();

  intb =
    bNum < 0
      ? Number(bStr + (Math.pow(10, resultNum) + '').replace('1', ''))
      : (function () {
          bStr = bStr.replace('.', '');
          bStr =
            resultNum == bSum
              ? bStr
              : bStr + (Math.pow(10, resultNum - bSum) + '').replace('1', '');
          return Number(bStr);
        })();
  switch (act) {
    case 'add': //加法
      return (inta + intb) / Math.pow(10, resultNum);
      break;
    case 'subtract': //减法
      return (inta - intb) / Math.pow(10, resultNum);
      break;
    case 'multiplication': //乘法
      // 乘法因为两边都放大了，所以结果要缩小2倍指数
      return (inta * intb) / Math.pow(10, resultNum * 2);
      break;
    case 'division': //除法
      return inta / intb;
      break;
  }
};

/**
 * [加法]
 * @return [结果]
 */
export const accAdd = (arg1, arg2) => {
  return floatCalc(arg1, arg2, 'add');
};

/**
 * [减法法]
 * @return [结果]
 */
export const accSub = (arg1, arg2) => {
  return floatCalc(arg1, arg2, 'subtract');
};

/**
 * [乘法]
 */
export const accMul = (arg1, arg2) => {
  return floatCalc(arg1, arg2, 'multiplication');
};

/**
 * [除法]
 * @return [结果]
 */
export const accDiv = (arg1, arg2) => {
  return floatCalc(arg1, arg2, 'division');
};

const digitsRE = /(\d{3})(?=\d)/g;

/**
 * value  金额
 * currency 货币符号
 * decimals  保留位数
 */
export function currency(v, c, d) {
  let value = parseFloat(v);
  if (!isFinite(value) || (!value && value !== 0)) return '';
  let curren = c != null ? c : '¥ ';
  let decimals = d != null ? d : 2;
  let stringified = Math.abs(value).toFixed(decimals);
  let _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
  let i = _int.length % 3;
  let head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : '';
  let _float = decimals ? stringified.slice(-1 - decimals) : '';
  let sign = value < 0 ? '-' : '';
  return sign + curren + head + _int.slice(i).replace(digitsRE, '$1,') + _float;
}
